<template>
  <div class="personnel-entry-exit-application bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">准入名单设置</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>


    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">新增</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <el-button @click="openImportDialog">导入</el-button>
      <el-button @click="exportData(applications, '准入名单', selectedIds)">导出</el-button>
    </div>


    <!-- Data Table -->

    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="HAZARDOUS_ITEM" label="危险品名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="CN_CODE" label="CN号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ITEM_TYPE" label="类别/项别" header-align="center" align="center"></el-table-column>
        <el-table-column prop="FORBIDDEN_ITEM" label="禁忌物" header-align="center" align="center"></el-table-column>
        <el-table-column prop="FIRE_RISK" label="火灾危险性" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PARK_NUM" label="停车位数" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HEAVYOREMPTY" label="空载/重载" header-align="center" align="center">
          <template #default="scope">
            {{ scope.row.HEAVYOREMPTY == 0 ? '空载' : '重载' }}
          </template>
        </el-table-column>
        <el-table-column prop="STAMP" label="备注" header-align="center" align="center"></el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editApplication(scope.row)" link>编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />

    <!-- Add/Edit Dialog -->
    <el-dialog class="dialog-from" v-model="isDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'" width="650"
      destroy-on-close align-center>
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-4">

            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">危险品名称</label>
              <el-input type="text" id="staffCode" v-model="formData.HAZARDOUS_ITEM" required class="input" />
            </div>
            <div>
              <label for="staffName" class="block text-sm font-medium text-muted-foreground">CN号</label>
              <el-input type="text" id="staffName" v-model="formData.CN_CODE" required class="input" />
            </div>
            <div>
              <label for="idCard" class="block text-sm font-medium text-muted-foreground">类别/项别</label>
              <el-input type="text" id="idCard" v-model="formData.ITEM_TYPE" required class="input" />
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">禁忌物</label>
              <el-input type="text" id="TELEPHONE" v-model="formData.FORBIDDEN_ITEM" required class="input" />
            </div>
            <div>
              <label for="TELEPHONE" class="block text-sm font-medium text-muted-foreground">火灾危险性</label>
              <el-select v-model="formData.FIRE_RISK" placeholder="请选择" clearable>
                <el-option label="甲类" value='甲类' />
                <el-option label="乙类" value='乙类' />
                <el-option label="丙类" value='丙类' />
                <el-option label="丁类" value='丁类' />
                <el-option label="戊类" value='戊类' />
              </el-select>
            </div>
            <div>
              <label for="staffGender" class="block text-sm font-medium text-muted-foreground">停车位数</label>
              <el-input type="text" id="TELEPHONE" v-model="formData.PARK_NUM" required class="input" />
            </div>
            <div>
              <label for="TELEPHONE" class="block text-sm font-medium text-muted-foreground">空载/重载</label>

              <el-select v-model="formData.HEAVYOREMPTY" placeholder="请选择" clearable>
                <el-option label="空载" value='0' />
                <el-option label="重载" value='1' />
              </el-select>
            </div>
          </div>
        </div>
        <!-- 其他信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>其他信息</span>
          </div>
          <div>
            <label class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" v-model="formData.STAMP" required class="input" />
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </form>
    </el-dialog>

    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <input accept=".csv, .xlsx" type="file" @change="handleFileUpload" />
      <div class="flex justify-end">
        <el-button @click="closeImportDialog">
          取消
        </el-button>
        <el-button type="primary" @click="importData">
          导入
        </el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

import { dayjs } from "element-plus"
import { exportData, checkval } from '#/utils/exportfile.js'
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/hazardous-item-support'
})

const search = ref({
  HAZARDOUS_ITEM: '',
  CN_CODE: ""
})
const isImportDialogOpen = ref(false)
const formItems = ref([
  {
    label: '危险品名称:',
    model: 'HAZARDOUS_ITEM',
    type: 'input',
    placeholder: '请输入',
  },

  {
    label: 'CN号:',
    model: 'CN_CODE',
    type: 'input',
    placeholder: '请输入',
  },

])
const importFile = ref(null)
const loading = ref(false)
const applications = ref([])
const selectAll = ref(false)
const isDialogOpen = ref(false)
const table = ref()
const isEditing = ref(false)
const formData = ref({})
const viewingItem = ref(null)
const displayedApplications = ref([])
const alltabledata = (data) => {
  displayedApplications.value = data
}
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const searchApplications = async () => {
  displayedApplications.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })

    applications.value = response.data.map(app => ({ ...app, selected: false }))
    applications.value.forEach((e) => {
      e.HEAVYOREMPTY = String(e.HEAVYOREMPTY)

    })
    updateSelectAllState()
  } catch (error) {
    console.error('搜索失败:', error)
    alert('搜索失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {
  search.value = {
    HAZARDOUS_ITEM: '',
    CN_CODE: ""
  }
  searchApplications()
}

const openAddDialog = () => {
  isDialogOpen.value = true
  isEditing.value = false
  formData.value = {}
}

const closeDialog = () => {
  isDialogOpen.value = false
}

const handleSubmit = async () => {


  if (checkval(['HAZARDOUS_ITEM',
    'CN_CODE',
    'ITEM_TYPE',
    'FORBIDDEN_ITEM',
    'FIRE_RISK',
    'PARK_NUM',
    'HEAVYOREMPTY',
    'STAMP',
  ], '准入名单', formData.value)) {
    return
  }





  formData.value.HEAVYOREMPTY = Number(formData.value.HEAVYOREMPTY)
  try {
    if (isEditing.value) {
      await axios.put(`${apiBaseUrl.value}/${formData.value.ID}`, formData.value)

    } else {
      await axios.post(`${apiBaseUrl.value}`, formData.value)

    }
    alert('提交成功')
    closeDialog()
    await searchApplications()
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {

  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(async item => {
        await axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchApplications()

    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const editApplication = (item) => {
  formData.value = {
    ID: item.ID,
    HAZARDOUS_ITEM: item.HAZARDOUS_ITEM,
    CN_CODE: item.CN_CODE,
    ITEM_TYPE: item.ITEM_TYPE,
    FORBIDDEN_ITEM: item.FORBIDDEN_ITEM,
    FIRE_RISK: item.FIRE_RISK,
    PARK_NUM: item.PARK_NUM,
    HEAVYOREMPTY: item.HEAVYOREMPTY,
    STAMP: item.STAMP,
  }
  isEditing.value = true
  isDialogOpen.value = true
}
const openImportDialog = () => {
  isImportDialogOpen.value = true
}


const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed') // 添加日志
}
const importData = async (file) => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/improve`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await allsearch()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}


const toggleSelectAll = () => {
  console.log('触发全选:', !selectAll.value)
  selectAll.value = !selectAll.value
  applications.value.forEach(app => {
    app.selected = selectAll.value
    console.log(`设置 ${app.ID} 的选中状态为:`, app.selected)
  })
}

const toggleItemSelection = (item) => {
  console.log('切换选中状态:', item.ID, !item.selected)
  item.selected = !item.selected
  updateSelectAllState()
}

const updateSelectAllState = () => {

  selectAll.value = applications.value.length > 0 && applications.value.every(app => app.selected)

}




const getStatusClass = (status) => {
  const classMap = {
    '未审核': 'bg-yellow-100 text-yellow-800',
    '已通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}



const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}





function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}


watch(applications, () => {

  updateSelectAllState()
}, { deep: true })

watch(selectAll, (newValue) => {
  // console.log('selectAll changed:', newValue)
  applications.value.forEach(app => {
    app.selected = newValue
    console.log('watch selectAll - 设置项目状态:', app.ID, app.selected)
  })
})

onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>

